package com.sabm.controller;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.security.authentication.encoding.PasswordEncoder;


import com.sabm.model.Account;
import com.sabm.model.Role;
import com.sabm.service.DatabaseService;

@Controller
public class AdminController {
	@Autowired
	private DatabaseService dbs;
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	@RequestMapping("/admin")
	public String showAdminPage(ModelMap model) {
		// account info
		Account account = (Account) SecurityContextHolder.getContext()
		.getAuthentication().getPrincipal();
		model.addAttribute("username", account.getUsername());
		//
		List<Account> accounts = dbs.getListAccounts();
		model.addAttribute("accounts",accounts);
		return "admin";
	}
	@RequestMapping(value="/addUser.do", method=RequestMethod.POST)
	public String addUser(ModelMap model, 
			@RequestParam(value = "username", required = true) String username,
			@RequestParam(value = "password", required = true) String password,
			@RequestParam(value = "role", required = true) String role,
			@RequestParam(value = "confpassword", required = true) String confpassword){
		if(!confpassword.equals(password)){
			model.addAttribute("message", "Confirm password is not correct!");
			return "forward:/admin";
		}
		if(dbs.checkUsername(username)){
			model.addAttribute("message", "This username existed! Please choose another.");
			return "forward:/admin";
		}
		//encrypt pass
		String encodedPassword = passwordEncoder.encodePassword(password, null);
		//
		Set<Role> setRole = new HashSet<Role>(0);
		setRole.add(new Role(role));
		Account newAccount = new Account(username,encodedPassword,null,setRole);
		try{
			dbs.addAccount(newAccount);
			model.addAttribute("message", "Add Successfully!");
		}catch(Exception e){
			model.addAttribute("message", "Error!");
		}
		return "forward:/admin";
	}
	// delete user
    @RequestMapping(value="/deleteUser.do", method=RequestMethod.GET)
    public String deleteUser(ModelMap model,
    		@RequestParam(value = "idAccount", required = true) int idAccount){ 
    	Account account = dbs.getAccount(idAccount);
    	dbs.deleteAccount(account);
    	model.addAttribute("message", "Deleted successfully!");
    	return "forward:/admin";
    }
}
